// Vue2版本的Toast组件，使用JSX语法
import Vue from 'vue';
import './ToastStyles.css';

// 创建Toast组件
const ToastComponent = {
  name: 'ToastMessage',
  props: {
    // 消息文本
    message: {
      type: String,
      default: ''
    },
    // 显示时间，单位毫秒
    duration: {
      type: Number,
      default: 3000
    },
    // 类型：success, error, warning, info
    type: {
      type: String,
      default: 'info',
      validator: (value) => ['success', 'error', 'warning', 'info'].includes(value)
    },
    // 位置：top, bottom, top-left, top-right, bottom-left, bottom-right
    position: {
      type: String,
      default: 'top',
      validator: (value) => [
        'top', 'bottom', 'top-left', 'top-right', 'bottom-left', 'bottom-right'
      ].includes(value)
    }
  },
  
  data() {
    return {
      visible: false
    };
  },
  
  mounted() {
    // 组件挂载时显示Toast
    this.show();
  },
  
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
  },
  
  methods: {
    // 显示Toast
    show() {
      this.visible = true;
      
      if (this.duration > 0) {
        // 设置自动关闭定时器
        this.timer = setTimeout(() => {
          this.hide();
        }, this.duration);
      }
    },
    
    // 隐藏Toast
    hide() {
      this.visible = false;
      this.$emit('close');
    },
    
    // 获取图标
    getIcon() {
      switch (this.type) {
        case 'success':
          return '✅';
        case 'error':
          return '❌';
        case 'warning':
          return '⚠️';
        case 'info':
        default:
          return 'ℹ️';
      }
    },
    
    // 获取位置样式类
    getPositionClass() {
      return `toast-${this.position}`;
    }
  },
  
  // 使用JSX渲染函数
  render() {
    if (!this.visible) {
      return null;
    }
    
    return (
      <transition name="toast-fade">
        <div 
          class={['toast', `toast-${this.type}`, this.getPositionClass()]}
          onClick={this.hide}
        >
          <span class="toast-icon">{this.getIcon()}</span>
          <span class="toast-message">{this.message}</span>
        </div>
      </transition>
    );
  }
};

// 管理Toast实例的队列
const toastQueue = [];

// 安全地移除DOM节点的辅助函数
const safeRemoveElement = (element) => {
  if (element && element.parentNode) {
    element.parentNode.removeChild(element);
    return true;
  }
  return false;
};

// 创建Toast实例的工厂函数
const createToast = (options) => {
  // 创建挂载点
  const mountNode = document.createElement('div');
  document.body.appendChild(mountNode);
  
  // 创建Vue实例
  const instance = new Vue({
    render(h) {
      return h(ToastComponent, {
        props: options,
        on: {
          close: () => {
            // 关闭后移除DOM
            setTimeout(() => {
              instance.$destroy();
              safeRemoveElement(mountNode);
              // 从队列中移除
              const index = toastQueue.findIndex(item => item.mountNode === mountNode);
              if (index !== -1) {
                toastQueue.splice(index, 1);
              }
            }, 300); // 等待过渡动画结束
          }
        }
      });
    }
  });
  
  // 挂载Vue实例
  instance.$mount(mountNode);
  
  // 创建Toast对象
  const toast = {
    mountNode,
    instance,
    close: () => {
      instance.$destroy();
      safeRemoveElement(mountNode);
      // 从队列中移除
      const index = toastQueue.findIndex(item => item.mountNode === mountNode);
      if (index !== -1) {
        toastQueue.splice(index, 1);
      }
    }
  };
  
  // 添加到队列
  toastQueue.push(toast);
  
  return toast;
};

// 导出Toast方法
export const toast = {
  info(message, duration = 3000, position = 'top') {
    return createToast({ message, duration, type: 'info', position });
  },
  success(message, duration = 3000, position = 'top') {
    return createToast({ message, duration, type: 'success', position });
  },
  error(message, duration = 3000, position = 'top') {
    return createToast({ message, duration, type: 'error', position });
  },
  warning(message, duration = 3000, position = 'top') {
    return createToast({ message, duration, type: 'warning', position });
  },
  // 清除所有Toast
  clear() {
    toastQueue.forEach(toast => {
      toast.instance.$destroy();
      safeRemoveElement(toast.mountNode);
    });
    toastQueue.length = 0;
  }
};

// 创建Vue插件
export const ToastPlugin = {
  install(Vue) {
    Vue.prototype.$toast = toast;
  }
};

// 导出组件
export default ToastComponent; 